package concurrencyPractice.chapter07;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 7-1 使用volatile来保存取消状态
 * @date 2024/1/4 15:43:32
 */
public class PrimeGenerator implements Runnable{

    private final List<BigInteger> primes = new ArrayList<>();
    private volatile boolean cancelled;

    public void run() {
        BigInteger p = BigInteger.ONE;
        while (!cancelled) {
            p = p.nextProbablePrime();
            synchronized (this) {
                primes.add(p);
            }
        }
    }

    public void cancel() {
        cancelled = true;
    }
    public synchronized List<BigInteger> get() {
        return new ArrayList<>(primes);
    }
}
